package com.fa4j.product.comment.service.impl;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.product.comment.convert.CommentConverter;
import com.fa4j.product.comment.model.Comment;
import com.fa4j.product.comment.model.CommentCreateCmd;
import com.fa4j.product.comment.repository.CommentRepository;
import com.fa4j.product.comment.service.CommentService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Optional;

/**
 * 服务实现-商品评论
 *
 * @since 2025-11-22 21:06:24
 */
@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final CommentRepository commentRepository;
    private final CommentConverter commentConverter;


    /**
     * 商品评论-删除
     *
     * @param cmd 删除参数
     * @return 商品评论
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Comment remove(@Valid RemoveCmd<Long> cmd) {
        Comment entity = commentRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("商品评论"));
        entity.setOperatorId(cmd.getOperatorId());
        commentRepository.remove(entity);
        return entity;
    }

    /**
     * 商品评论-提交评论
     *
     * @param cmd 创建参数
     * @return 商品评论
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Comment submit(@Valid CommentCreateCmd cmd) {
        Optional<Comment> commentOpt = commentRepository.countByOrderIdAndSpecId(cmd.getOrderId(), cmd.getSpecId());
        if (commentOpt.isPresent()) {
            throw CommonRequestError.BAD_REQUEST.build("该订单商品已经评论");
        }
        Comment entity = commentConverter.toEntity(cmd);
        commentRepository.create(entity);
        return entity;
    }


}






